﻿var tsproing;
var istsing;
var pageTstimer = null;
var isStart = false;
var isOut = false;
var probeId = null;
var session = null;
var account = null;
var workIp = null;
var serverInfo = null;//所有节点服务器
var countTimer = 0;
var type = "5";
var collectType = "3";
var currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
var speedvalue = -212;//网络速度。
var clickbegin = false;
var speedcomp;
var urls;
var thredNum;
var downTime;
var singleTime;
var ignoreTime;
var single;
var paramObj = null;
var prevSize = 0;
var ignoreTimeLen = $('#ignoreTimeLen', parent.document).val();//单次频率
var rate = $('#rate', parent.document).val();//单次频率
var isDouble = $('#isDouble', parent.document).val();//是否增加倍数
$(function () {
	var orgName = $('#orgName', parent.document).val();
	if (orgName != null && orgName != "") {
		isStart = true;
		$("#begin_test").attr("disabled", "disabled");
		$("#imgingId").attr("src", base + "/libs/pageImages/test_checking.gif");
		var ip = $('#ipId', parent.document).val();
		var signWidth = $('#signWidth', parent.document).val();
		var speedWidth = $('#speedWidth', parent.document).val();

		$("#topIpId").html(ip);
		$("#topOrgNameId").html(orgName);
		$("#broadband_account").html($('#account', parent.document).val());
		$("#speedup_broadband").html(speedWidth);
		$("#signing_broadband").html(signWidth);
		$("#bottonIpId").html(ip);
		$("#bottonOrgNameId").html(orgName);
		$("#k_account").html($('#account', parent.document).val());
		$("#signWidthId").html(signWidth);
		$("#speedWidthId").html(speedWidth);

		callIntegerFace();
		isStart = true;
		clickbegin = true;
	} else {
		var internetId = $('#internetId', parent.document).val();
		$("#unitId").html(speedUtil.rateUtil);
		getIpQuery();

	}
	$("#begin_test").click(function () {
		if (isStart == true) {
			$("#content_test2").hide();
			$("#agreement_test2").show();
			$("#begin_test").attr("disabled", "disabled");
			$("#cencal_begin_test").removeAttr("disabled");
			$("#xy_checkItem").removeAttr("checked");
		} else {
			alert("带宽信息获取失败,不能测速");
		}
	});

	//是否勾选同意协议
	$("#xy_checkItem").click(function () {
		if ($("#xy_checkItem").is(":checked")) { //jQuery方式判断
			$("#begin_test").attr("disabled", "disabled");
			$("#ok_begin_test").removeAttr("disabled");
			$("#cencal_begin_test").removeAttr("disabled");
		} else {
			$("#ok_begin_test").attr("disabled", "disabled");
			$("#cencal_begin_test").attr("disabled", "disabled");
			$("#begin_test").removeAttr("disabled");
		}
	});


	$("#ok_begin_test").click(function () {
		$("#content_test2").show();
		$("#agreement_test2").hide();
		$("#begin_test").removeAttr("disabled");
		$("#ok_begin_test").attr("disabled", "disabled");
		begintest();
	})

	//取消协议测速
	$("#cencal_begin_test").click(function () {
		$("#content_test2").show();
		$("#agreement_test2").hide();
		$("#begin_test").removeAttr("disabled");
		$("#ok_begin_test").attr("disabled", "disabled");
		$("#cencal_begin_test").attr("disabled", "disabled");
	})

	$("#reStartTs").click(function () {
		$("#begin_test").attr("disabled", "disabled");
		$("#imgingId").attr("src", base + "/libs/pageImages/test_checking.gif");
		$(".testing-header").show();
		$(".testing-result").hide();
		$(".ingspeed b").html("0.00");
		$("#unitId").html(speedUtil.rateUtil);
		tsproing = "no";
		$("#childTsId", parent.document).val(tsproing);
		$("#teststepone").show();
		$("#teststeptwo").hide();
		callIntegerFace();
		isStart = true;
	});

});

//开始测试 
function begintest() {
	if (paramObj != null && paramObj != "") {
		tsproing = "yes";
		$("#childTsId", parent.document).val(tsproing);
		$("#teststepone").hide();
		$("#teststeptwo").show();
		//$('#rimg').rotate({angle:145});
		clickbegin = true;
		console.info(paramObj);
		commonNodeQuate(paramObj);
	} else {
		alert("测速节点网络质量获取失败.");
		return;
	}
}

function commonNodeQuate(obj) {
	//所有节点网络质量上报，生成下载文件
	$.ajax({
		type: "POST",
		url: base + "/servlet/pushServerQualityIndex?d=" + Math.random(),
		dataType: "JSON",
		data: { "jsonParam": obj },
		success: function (data) {
			if (data.status == 1) {
				pageTstimer = setInterval(function () {
					getNodePathObj();
				}, 2000);
			} else {
				tsproing = "no";
				$("#childTsId", parent.document).val(tsproing);
				$("#teststepone").show();
				$("#teststeptwo").hide();
				alert("所有节点网络质量上报错误.");
			}
		},
		error: function (xhr, status, error) {
			tsproing = "no";
			$("#childTsId", parent.document).val(tsproing);
			$("#teststepone").show();
			$("#teststeptwo").hide();
			alert("所有节点网络质量上报请求错误.");
		}
	});
}

//获取最新命令
function getNodePathObj() {
	var ipP = $('#ipId', parent.document).val();
	var probeIdP = $('#probeId', parent.document).val();
	var sessionP = $('#session', parent.document).val();
	var accountP = $('#account', parent.document).val();
	var obj = {};
	obj.probeId = (probeId != null ? probeId : probeIdP);
	obj.type = type;
	obj.collectType = collectType;
	obj.session = (session != null ? session : sessionP);
	obj.cmdId = 10;
	obj.account = (account != null ? account : accountP);
	obj.terminalIp = (workIp != null ? workIp : ipP);
	obj.currentTime = currentTime;
	$.ajax({
		type: "POST",
		url: base + "/servlet/latestCommand?d=" + Math.random(),
		dataType: "JSON",
		async: false,
		cache: false,
		data: { "jsonParam": JSON.stringify(obj) },
		success: function (data) {
			if (data == null) {
				countTimer++;
				//继续执行定时器
				if (countTimer == 5) {
					//如果请求次数达到了7次。则关闭定时器
					clearInterval(pageTstimer);
					$("#teststepone").show();
					$("#teststeptwo").hide();
					countTimer = 0;
					tsproing = "no";
					$("#childTsId", parent.document).val(tsproing);
					alert("测速地址信息生成失败.");
				}
			} else {
				//关闭定时器
				clearInterval(pageTstimer);
				countTimer = 0;
				if (data.status == 1) {
					//命令获取成功
					var obj = data.cmdParam;
					urls = obj.downAddress;
					thredNum = obj.thredNum;
					downTime = obj.downTime * 1000;
					singleTime = obj.singleTime * 1000;
					ignoreTime = obj.ignoreTime;
					single = obj.singleTime;
					startDownload(urls, thredNum, downTime, singleTime, obj.downHAddress);
				} else {
					//命令获取失败
					$("#teststepone").show();
					$("#teststeptwo").hide();
					tsproing = "no";
					$("#childTsId", parent.document).val(tsproing);
					alert("获取最新命令失败.原因：" + data.msg);
				}
			}
		},
		error: function (xhr, status, error) {
			tsproing = "no";
			$("#childTsId", parent.document).val(tsproing);
			countTimer = 0;
			$("#teststepone").show();
			$("#teststeptwo").hide();
			alert("获取最新命令请求错误.");
		}
	});
}

/**
 * 环境预检与获取所有节点信息接口
 */
function callIntegerFace() {
	var obj = {};
	if (probeId == null) {
		probeId = $('#probeId', parent.document).val();
	}
	if (session == null) {
		session = $('#session', parent.document).val();
	}
	if (account == null) {
		account = $('#account', parent.document).val();
	}
	if (workIp == null) {
		workIp = $('#ipId', parent.document).val();
	}
	obj.probeId = probeId;
	obj.type = type;
	obj.collectType = collectType;
	obj.session = session;
	obj.account = account;
	obj.terminalIp = workIp;
	obj.currentTime = currentTime;
	obj.cmdId = 8;
	obj.detectResult = 0;

	obj.speedType = "H5";

	//环境预检
	$.ajax({
		type: "POST",
		url: base + "/servlet/pushCheckSurroUpload?d=" + Math.random(),
		dataType: "JSON",
		async: false,
		data: { "jsonParam": JSON.stringify(obj) },
		success: function (data) {
			if (data.status == 1) {
				//获取所有的节点信息
				delete obj.cmdId;
				delete obj.detectResult;
				$.ajax({
					type: "POST",
					url: base + "/servlet/testAllAdrUpload?d=" + Math.random(),
					dataType: "JSON",
					data: { "jsonParam": JSON.stringify(obj) },
					success: function (data) {
						if (data.status == 1) {
							serverInfo = data.serverInfo;
							$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");

							var flishObj = {};
							flishObj.probeId = $('#probeId', parent.document).val();
							flishObj.type = type;
							flishObj.collectType = collectType;
							flishObj.session = $('#session', parent.document).val();
							flishObj.cmdId = 9;
							var array = new Array();
							if (serverInfo != null && serverInfo.length >= 1) {
								var count = 0;
								getNodeDelay(array, serverInfo, count, flishObj);
							}
						} else {
							$("#begin_test").removeAttr("disabled");
							$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");
							alert("获取所有节点错误.");
						}
					},
					error: function (xhr, status, error) {
						$("#begin_test").removeAttr("disabled");
						$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");
						alert("获取所有节点请求错误.");
					}
				});
			} else {
				$("#begin_test").removeAttr("disabled");
				$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");
				alert("环境预检错误.");
			}
		},
		error: function (xhr, status, error) {
			$("#begin_test").removeAttr("disabled");
			$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");
			alert("环境预检请求错误.");
		}
	});
}



function getNodeDelay(array, serverInfo, count, flishObj) {
	var nodeObj = {};
	nodeObj.nodeName = serverInfo[count].serverName;//探针ID
	nodeObj.nodeIp = serverInfo[count].serverIp;//服务器IP
	//域名响应开始时间
	var startTime = +new Date();
	var delay = 0;
	var url = serverInfo[count].serverUrl;
	count++;
	$.ajax({
		url: url + "?d=" + Math.random(),
		timeout: 2000, //超时时间设置，单位毫秒
		dataType: "jsonp",/*加上datatype*/
		contentType: "application/json",
		processData: false,
		type: 'post',
		async: true,//异步
		cache: false,
		success: function (data) {
			delay = (new Date() - startTime);//响应时间
			nodeObj.delay = delay;
			array.push(nodeObj);
			if (count == serverInfo.length) {
				flishObj.serverInfo = array;
				paramObj = JSON.stringify(flishObj);
				$("#begin_test").removeAttr("disabled");
				$('#parmObj', parent.document).val(JSON.stringify(flishObj));

				return;
			} else {
				getNodeDelay(array, serverInfo, count, flishObj);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			if (XMLHttpRequest.status == 200 && XMLHttpRequest.readyState == 4) {
				delay = (new Date() - startTime);//响应时间
			} else {
				delay = 999999;
			}
			nodeObj.delay = delay;
			array.push(nodeObj);
			if (count == serverInfo.length) {
				flishObj.serverInfo = array;
				paramObj = JSON.stringify(flishObj);
				$("#begin_test").removeAttr("disabled");
				$('#parmObj', parent.document).val(JSON.stringify(flishObj));
				begintest();
				return;
			} else {
				getNodeDelay(array, serverInfo, count, flishObj);
			}
		}
	});

}



/**
 *认证模式与IP反查接口调用
 */
function getIpQuery() {
	istsing = "yes";
	$('#istsing', parent.document).val(istsing);
	countTimer = 0;
	var ip = $('#ipId', parent.document).val();
	var obj = {};
	obj.type = type;
	obj.collectType = collectType;
	obj.terminalIp = ip;
	obj.currentTime = currentTime;
	//认证模式获取
	$.ajax({
		type: "POST",
		url: base + "/servlet/pushAuthTypeIndex",
		dataType: "JSON",
		data: { "jsonParam": JSON.stringify(obj) },
		success: function (data) {
			if (data.status == 1) {
				var authType = data.authType;
				if (authType == 1) {
					//认证模式==1>>IP反查
					$.ajax({
						type: "POST",
						url: base + "/servlet/pushIpCheckIndex",
						dataType: "JSON",
						data: { "jsonParam": JSON.stringify(obj) },
						success: function (data) {
							istsing = "no";
							$('#istsing', parent.document).val(istsing)
							$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");
							if (data.status == 1) {
								var ip = data.terminalIp;
								var orgName = data.regionName;
								var dbCode = data.dbCode;
								var confCode = data.confCode;
								probeId = data.probeId;
								session = data.session;
								account = data.account;
								var ip = $('#ipId', parent.document).val();
								workIp = ip;
								$("#topIpId").html(workIp);
								$("#topOrgNameId").html(orgName);
								$("#bottonIpId").html(ip);
								$("#bottonOrgNameId").html(orgName);

								$('#orgName', parent.document).val(orgName);

								$('#probeId', parent.document).val(probeId);
								$('#session', parent.document).val(session);
								$('#account', parent.document).val(account);
								$("#k_account").html(account);

								$('#broadband_account').html(account);

								if (dbCode != 0 && dbCode != null && dbCode != '' && dbCode != undefined) {
									$("#signWidthId").html(dbCode + "M");
									$('#signWidth', parent.document).val(dbCode + "M");
									$('#signing_broadband').html(dbCode + "M");
									$('#speedWidthId').html(confCode + "M");
									$('#speedWidth', parent.document).val(confCode + "M");
									$('#speedup_broadband').html(confCode + "M");
								} else {
									$("#signWidthId").html("");
									$('#signWidth', parent.document).val("");
									$('#signing_broadband').html("");
									$('#speedup_broadband').html("");
								}
								if (account != null && account != '' && account != undefined) {
									callIntegerFace();
									isStart = true;

								} else {
									istsing = "no";
									alert("您办理的宽带套餐不属于联通宽带测速范围，暂不能使用测速服务。\r\n若需使用，请到营业渠道变更宽带套餐。");
								}
							} else {
								$("#topIpId").html($('#ipId', parent.document).val());
								$("#topOrgNameId").html("未知");
								alert("没有获取到宽带信息,不能进行测速.");
							}
						},
						error: function (xhr, status, error) {
							istsing = "no";
							$('#istsing', parent.document).val(istsing)
							$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");
							alert("IP反查请求错误.");
						}
					});
				}
			} else {
				istsing = "no";
				$('#istsing', parent.document).val(istsing)
				$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");
				alert("认证模式获取错误.");
			}
		},
		error: function (xhr, status, error) {
			istsing = "no";
			$('#istsing', parent.document).val(istsing)
			$("#imgingId").attr("src", base + "/libs/pageImages/test_check.png");
			alert("认证模式请求错误.");
		}
	});
}

var arrayReq = new Array();//ajax文件下载数组
var intervalue = 0;
var totalNum = 0;
var num = 1;
var avg = 0;
var startTime = 0;//执行开始时间
var oldTotalNum = 0;

function startDownload(urls, thredNum, downTime, singleTime, downHAddress) {
	arrayReq = new Array();
	totalNum = 0;
	num = 1;
	avg = 0;
	oldTotalNum = 0;
	isJxSpeed = true;
	for (var i = 1; i <= thredNum; i++) {
		setTimeout(ajaxDownload(i, downHAddress), 0);
	}
	startTime = new Date().getTime()
	intervalue = setInterval('currentSpeedRate(' + downTime / 1000 + ')', singleTime);
}

function closeAjaxDownload() {
	isJxSpeed = false;
	clearInterval(intervalue);
	for (var i = 0; i < arrayReq.length; i++) {
		var xhr = arrayReq[i];
		xhr.abort();
	}
}

function ajaxDownload(val, downHAddress) {
	//方案一
	var oldTotalSize = 0;
	var url = downHAddress + "?ran=" + Math.random();
	var xhr = new XMLHttpRequest();
	xhr.open("POST", url, true);
	xhr.onprogress = function (evt) {
		//方案一
		var sj = evt.loaded - oldTotalSize;
		totalNum = totalNum + sj;
		oldTotalSize = evt.loaded;
		if (!isJxSpeed) {
			xhr.abort();
			//setTimeout(ajaxDownload(val),0);
		}
	};
	xhr.onerror = function (evt) { };//请求失败
	xhr.responseType = "blob";
	xhr.onreadystatechange = function (e) {
		if (xhr.readyState == 4 && xhr.status == 200) {

		}
	};
	xhr.send(null);
	arrayReq.push(xhr);
}

function currentSpeedRate(downTime) {
	if (num <= downTime) {
		//方案一
		var endTime = new Date().getTime();
		var speedRate = totalNum - oldTotalNum;
		speedRate = speedRate / (endTime - startTime);
		speedRate = speedRate * 1000;// / 1024 / 1024 * 8;
		if (num > 1) {
			if (speedRate < oldSpeedRate) {
				var avgSpeedRate = (speedRate + oldSpeedRate) / 2;
				if (avgSpeedRate > speedRate) {
					speedRate = avgSpeedRate;
				}
			}
		}
		oldSpeedRate = speedRate;
		downSpeed(speedRate);//设置速度到界面进行呈现

		oldTotalNum = totalNum;
		startTime = endTime;
		//将消息显示在网页上
	} else {
		closeAjaxDownload();
		downComplete();
	}
	num++;
}

/****flash 推送测速结果，页面呈现并保存****/
var count = 1;
var downArray = new Array();
var addTotal = 0;
function downSpeed(value) {
	if (value >= 0) {
		addTotal = addTotal + single;
		var speed = value;
		var obj = {};
		obj.avgDownRate = speed;
		obj.maxRate = speed;
		obj.minRate = speed;
		obj.secNum = addTotal;
		downArray.push(obj);
		var size = speed / paramConf.rateConvert;//KBs
		if (size != 0) {
			var val = size.toFixed(2);
			if (speedUtil.operator == "/") {
				$(".ingspeed b").html(((val / paramConf.rateConvert) * 8).toFixed(2));
			} else if (speedUtil.operator == "*") {
				$(".ingspeed b").html((val * speedUtil.rateConvert).toFixed(2));
			} else {
				$(".ingspeed b").html(((val / paramConf.rateConvert) * 8).toFixed(2));
			}
			$(".ingspeed span").html(speedUtil.rateUtil);
		}
	} else {
		$(".ingspeed b").html("0.00");
		$(".ingspeed span").html(speedUtil.rateUtil);
	}

}


/*******测速完成******/
function downComplete() {
	$(".testing-header").hide();
	$(".testing-result").show();
	tsproing = "no";
	isOut = false;
	$("#childTsId", parent.document).val(tsproing);
	$("#going", parent.document).val("two");
	var probeIdP = $('#probeId', parent.document).val();
	var sessionP = $('#session', parent.document).val();
	//保存测速记录
	var obj = {};
	obj.probeId = (probeId != null ? probeId : probeIdP);
	obj.type = type;
	obj.collectType = collectType;
	obj.session = (session != null ? session : sessionP);
	obj.cmdId = 10;
	obj.singleTime = single;
	obj.ignoreTime = ignoreTime;
	obj.currentTime = currentTime;
	obj.downResults = downArray;
	obj.speedType = "H5";
	isStart = false;

	if (downArray == null || downArray == undefined || downArray == '') {
		alert("保存测速失败,请稍后在试!");
	} else {
		$.ajax({
			type: "POST",
			url: base + "/servlet/pushDownIndex?d=" + Math.random(),
			dataType: "JSON",
			data: { "jsonParam": JSON.stringify(obj) },
			success: function (data) {
				if (data.status == 1) {
					analyDownResult(data);
				} else {
					alert("保存测速记录错误");
				}
				downArray = new Array();
				addTotal = 0;
				prevSize = 0;
			},
			error: function (xhr, status, error) {
				downArray = new Array();
				addTotal = 0;
				prevSize = 0;
				alert("保存测速记录请求错误.");
			}
		});
	}
}


/**
 * 解析下行测速上报结果
 * @param sendData
 */
function analyDownResult(sendData) {
	if (sendData != null && sendData != '') {
		var maxR = "未知";
		if (sendData.maxRate != null) {
			maxR = sendData.maxRate;
		}
		var minR = "未知";
		if (sendData.minRate != null) {
			minR = sendData.minRate;
		}
		var avgR = "未知";
		if (sendData.avgDownRate != null) {
			avgR = sendData.avgDownRate;
		}
		$(".left-info p").html(maxR);
		$(".right-info p").html(minR);
		$(".bottom-info span").html(avgR);
		// 取配置带宽，进行泛值判断
		if (sendData.reachState == 1) {
			$("#wangluo_state").html("<label class='wangluo'>当前网络状况:</label><label class=\"embedtext text-orange\">很好</label>");
		} else if (sendData.reachState == 2) {
			$("#wangluo_state").html("<label class='wangluo'>当前网络状况:</label><label class='embedtext'>一般</label>");
		} else {
			$("#wangluo_state").hide();
		}
	}
}

